package chen.web.config;

import java.util.Map;
import java.util.Observable;

public class ConfigRepository extends Observable{
	
	private Map<Class<? extends Config>, Config> configs = new java.util.concurrent.ConcurrentHashMap<Class<? extends Config>, Config>();
	
	private ConfigRepository(){}

	private static ConfigRepository factory = null;
	
	static{
		init();
	}

	public static ConfigRepository instance(){
		return factory;
	}
	
	public <T extends Config> T get(Class<T> cls){
		return (T)configs.get(cls);
	}
	
	/**
	 * 此方法会自动将配置持久化
	 * @param config
	 */
	public void put(Config config){
		_put(config);
		this.setChanged();
		this.notifyObservers(config);
		config.persist();
	}
	
	private void _put(Config config){
		configs.put(config.getClass(), config);
	}
	
	private static void init(){
		factory = new ConfigRepository();
		Config[] list = configList();
		for(Config config : list){
			config.load();
			factory._put(config);
		}
	}
	
	private static Config[] configList(){
		return new Config[]{
			new EmailConfig(),
			new SiteConfig(),
			new IpTableConfig(),
			new UuidTableConfig(),
			new AccountTableConfig(),
			new SystemConfig()
		};
	}
}

